/**
 * Created by tanbingqin on 2019/12/2.
 */
import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Row, Col, Badge, Popover, Radio } from 'antd';
import ResizeTable from 'components/resize-table'
import SlideFrame from 'components/slide-frame'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import policyService from "containers/travel-standard/travel-standard.service"
import 'styles/custom-fields.scss'
import AdvancedTable from 'components/advanced-table'
const { SimpleTable } = AdvancedTable;
import NewScene from 'containers/travel-standard/new-scene'
import Priority from 'components/template/priority'
import RuleDetail from 'containers/travel-standard/rule-detail'

class SceneDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      scene: {}, //用餐类型详情
      searchForm: [
        {
          id: 'levelCode',
          label: messages('request-1.key726')/*层级*/,
          component: <Radio.Group>
            <Radio value="ALL">{messages('common.all')/*全部*/}</Radio>
            <Radio value="COMPANY">{messages('request-1.key725')/*公司*/}</Radio>
            <Radio value="SET_OF_BOOK">{messages('request-1.key743')/*帐套*/}</Radio>
          </Radio.Group>,
          initialValue: 'ALL',
          dataIndex: 'levelCode',
          parser: value => ({
            levelCode: value !== 'ALL' ? value : undefined
          }),
          tagParser: value => {
            if (value === 'ALL') {
              return messages('common.all')/*全部*/;
            } else {
              return value === "COMPANY" ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/;
            }
          }
        },
        {
          id: 'levelOrgId',
          dataIndex: 'levelName',
          label: messages('request-1.key727')/*所属组织*/,
          parser: value => ({
            levelOrgId: value ? (value.range === 'SET_OF_BOOK' ? value.rangeValue.setOfBooksId : value.rangeValue.id) : undefined
          }),
          tagParser: value => {
            if (value && value.range === 'SET_OF_BOOK') {
              return value.rangeValue.setOfBooksName;
            }
            if (value && value.range === 'COMPANY') {
              return value.rangeValue.name;
            }
          },
          component: <Priority onlySetOfBooks />,
        },
        {
          id: 'ruleName', label: messages('request-1.key326')/*名称*/, component: 'Input', dataIndex: 'comment',
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'travelRuleCompanyList',
          label: messages('request-1.key744')/*启用公司*/,
          component: 'Chooser',
          props: {
            labelKey: 'name',
            valueKey: 'id',
            type: 'priority_company'
          },
          dataIndex: 'travelRuleCompanyList',
          parser: value => ({
            companyIds: value ? value.map(item => item.id) : undefined
          })
        }
      ],
      columns: [
        {
          title: messages('request-1.key726')/*层级*/,
          dataIndex: 'levelCode',
          render: (value, record) => {
            return value === "COMPANY" ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/
          }
        },
        {
          title: messages('request-1.key727')/*所属组织*/,
          dataIndex: 'levelName',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key744')/*启用公司*/,
          dataIndex: 'travelRuleCompanyList',
          width: '10%',
          render: (value,record) => (
            this.renderCompany(value, record)
          )
        },
        {
          title: messages('request-1.key326')/*名称*/,
          dataIndex: 'comment',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-1.key745')/*适用人员*/,
          dataIndex: 'travelRuleRelations',
          width: '15%',
          render: (value,record) => (
            this.renderUser(value,record)
          )
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: 'status', width: '10%', align: "right",
          render: (value,record) => (
            <Badge
              status={value === 1001 ? 'success' : 'error'}
              text={value === 1001 ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            />
          )
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', key: 'operation', align: "center",
          render: (text, record) => (
            <span>
              {!record.readOnly && (
                <span>
                  <a onClick={(e) => this.handleNewEdit(e, record)}>{messages('common.edit.copy')/*复制并编辑*/}</a>
                  <span className="ant-divider"/>
                  <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('request-1.key386')/*你确认要删除？*/}>
                    <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a>
                  </Popconfirm>
                </span>
              )}
            </span>
          )
        }
      ],
    }
  }

  //复制并编辑
  handleNewEdit = (e, record) => {
    e.preventDefault();
    e.stopPropagation();
    const { tab } = this.state;
    const { params } = this.props;
    //复制要把id置空
    let resultRecord = JSON.parse(JSON.stringify(record));
    resultRecord.id = null;
    SlideFrame.open({
      title: messages('request-1.key747')/*新建标准*/,
      content: RuleDetail,
      afterClose: this.handleCloseStandardSlide,
      params: {
        travelType: 1010,
        record: resultRecord,
        sceneId: params.sceneId
      }
    }, this);
  };

  //删除
  handleDelete = (e, record) => {
    travelPolicyService.deleteTravelStandardRule(record.id).then(resp => {
      if (resp.status === 200){
        message.success(messages('common.delete.successful')/*删除成功*/);
        this.simpleTableRef.getList(true, 1);
      }
    }).catch(e => {
      errorMessage(e.response);
    })
  };

  componentDidMount(){
    this.getSceneDetail();
  }

  getSceneDetail = () => {
    const { params } = this.props;
    travelPolicyService.getSceneDetail(params.sceneId).then(res => {
      this.setState({scene: res.data});
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  //表格渲染启用公司
  renderCompany = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      if (value) {
        value.map((item, index) => {
          if (item.companyId) {
            relationNameList.push(item.companyName);
          }
        });
      }
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('request-1.key735')/*通用*/}</span>
    }
  };

  //表格渲染适用人员
  renderUser(value, record){
    if (value && value.length) {
      if (value[0].type === 1001){
        return <span>{messages('request-1.key735')/*通用*/}</span>
      }else {
        let relationNameList = [];
        if (value) {
          value.map((item, index) => {
            if (item.relationOID) {
              relationNameList.push(item.relationName);
            }
          });
        }
        return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
      }
    } else {
      return null;
    }
  };

  renderVisibleForms = () => {
    const { scene } = this.state;
    let visibleFormNameList = [];
    scene.visibleForms && scene.visibleForms.map(form => {
      visibleFormNameList.push(form.formName);
    });
    return visibleFormNameList.join(', ');
  };

  service = (page, pageSize, searchParams) => {
    const { params } = this.props;
    const { tab } = this.state;
    let listParams = {
      diningSceneId: params.sceneId,
      page,
      size: pageSize,
      travelType: 1010,
      ...searchParams
    };
    return policyService.getDiningRuleList(listParams);
  };

  //编辑用餐类型
  handleEdit = () => {
    const { scene } = this.state;
    SlideFrame.open({
      title: messages('request-1.key786')/*编辑类型*/,
      content: NewScene,
      afterClose: this.handleCloseSceneSlide,
      params: {
        travelType: 1010,
        record: JSON.parse(JSON.stringify(scene))
      }
    }, this);
  };

  //isSuccess是否是保存成功的关闭，如果是，则要刷新用餐类型详情
  handleCloseSceneSlide = (isSuccess) => {
    isSuccess && this.getSceneDetail();
  };

  handleRowClick = (record) => {
    const { params } = this.props;
    SlideFrame.open({
      title: messages('request-1.key748')/*编辑标准*/,
      content: RuleDetail,
      afterClose: this.handleCloseStandardSlide,
      params: {
        travelType: 1010,
        sceneId: params.sceneId,
        record
      }
    }, this);
  };

  //新建用餐的差标规则
  handleNew = () => {
    const { params } = this.props;
    const { scene } = this.state;
    SlideFrame.open({
      title: messages('request-1.key747')/*新建标准*/,
      content: RuleDetail,
      afterClose: this.handleCloseStandardSlide,
      params: {
        travelType: 1010,
        sceneId: params.sceneId,
        scene
      }
    }, this);
  };

  handleCloseStandardSlide = (success) => {
    success && this.simpleTableRef.getList(true, 1);
  };

  handleBack = () => {
    window.history.go(-1);
  };

  render() {
    const { scene, columns, searchForm } = this.state;
    return (
      <div className="full-height-page full-page-margin">
        <SimpleTable
          columns={columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="id"
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          onRef={ref => this.simpleTableRef = ref}
          tableName='travel-standard-dining-list'
          expandAll
          footer={
            <span>
              <a style={{fontSize:'14px', display: 'inline-block'}} onClick={this.handleBack}>
                <Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')/*返回*/}
              </a>
            </span>
          }
        >
          <div className="table-header">
            <div>
              <div className="header-title" style={{marginBottom: '12px'}}>
                {messages('request-1.key509')/*用餐类型*/}
                {!scene.readOnly && (
                  <span className='default-color-font' style={{fontSize: 12, display: 'inline-block', marginLeft: 20, cursor: 'pointer'}} onClick={this.handleEdit}>
                    {messages('common.edit')/*编辑*/}
                  </span>
                )}
              </div>
              <Row className="custom-form-row">
                <Col span={8}>
                  <div className="field-name">{messages('common.column.status')/*状态*/}</div>
                  <div className="field-content">{scene.status === 1 ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}</div>
                </Col>
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key726')/*层级*/}</div>
                  <div className="field-content">{scene.levelCode === 'COMPANY' ? messages('request-1.key725')/*公司*/ : messages('request-1.key743')/*帐套*/}</div>
                </Col>
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key727')/*所属组织*/}</div>
                  <div className="field-content">{scene.levelName}</div>
                </Col>
              </Row>
              <Row className="custom-form-row">
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key765')/*类型名称*/}</div>
                  <div className="field-content">{scene.name}</div>
                </Col>
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key746')/*适用表单*/}</div>
                  <div className="field-content">{scene.visibleFormScope === 1 ? messages('request-1.key735')/*通用*/ : this.renderVisibleForms()}</div>
                </Col>
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key766')/*可用时段*/}</div>
                  {scene.durationType && (
                    <div className="field-content">
                      {scene.durationType === 1 ? messages('request-1.key378')/*全天*/ : `${scene.startTime} - ${scene.endTime}`}
                    </div>
                  )}
                </Col>
              </Row>
              <Row className="custom-form-row">
                <Col span={8}>
                  <div className="field-name">{messages('request-1.key768')/*用餐频次*/}</div>
                  <div className="field-content">{scene.frequency === 1002 ? messages('request-1.key380')/*每天*/ : messages('request-1.key381')/*单次*/}</div>
                </Col>
              </Row>
              <div style={{background: '#F0F2F5', height: 10, margin: '20px -20px'}}></div>
            </div>
            <div className="table-header-buttons">
              <Button type="primary" onClick={this.handleNew}>
                {messages('request-1.key747')/*新建标准*/}
              </Button>
            </div>
          </div>
        </SimpleTable>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {

  }
}

SceneDetail.propTypes = {};

SceneDetail.defaultProps = {};

export default connect(mapStateToProps)(SceneDetail);
